from flask import jsonify, request, json, flash, render_template

from app.forms.book import SearchForm
from app.libs.helper import is_isbn_or_key
from app.spider.yushu_book import YuShuBook
from app.viewmodels.book import BookCollection, BookViewModel
from . import web


@web.route("/book/search")
def search():
    # Request Response
    # HTTP 的请求信息
    # q = request.args['q']
    # page = request.args['page']
    # 验证层
    form = SearchForm(request.args)

    if not form.validate():
        # return jsonify(form.errors)
        flash('搜索的关键字不符合要求,请重新输入关键字')
    q = form.q.data.strip()
    isbn_or_key = is_isbn_or_key(q)

    books = BookCollection()
    yushu_book = YuShuBook()

    if isbn_or_key == 'isbn':
        yushu_book.search_by_isbn(q)
    else:
        page = form.page.data
        yushu_book.search_by_key(q, page)

    books.fill(yushu_book, q)
    # return json.dumps(books, default=lambda o: o.__dict__)
    return render_template('search_result.html', books=books)

@web.route('/book/<isbn>/detail')
def book_detail(isbn):
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    book = BookViewModel(yushu_book.first)
    return render_template('book_detail.html',book =book,wishes=[],gifts=[])
